package ssm.Filter;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import ssm.Pojo.YzUsers;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

public class BUnLogin implements HandlerInterceptor {
    /**
     * 定义用户未登录，但有必要放行的URI
     */
    private static final String[] IGNORE_URI={"user/login"};

    /**
     * 该方法是在Controller执行之前调用的
     * 若该方法返回true:则会继续执行postHandle和afterCompletion
     * 若该方法返回false:整个请求结束
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        // 获得用户请求的URI
        String requestURI=request.getRequestURI();//URI=/WebLogin/html/login.html 即工程名+目标资源路径
        String requestPath=request.getServletPath();//URL=login.html 即目标资源名称
        YzUsers u = (YzUsers) request.getSession().getAttribute("user");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if(u == null){
            response.setHeader("content-type","application:json;charset=utf8");
            JSONObject json =unLogin(request);
            response.getWriter().write(json.toJSONString());
            return false;
        }
        return true;
    }

    public JSONObject unLogin(HttpServletRequest request){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        JSONObject json=new JSONObject();
        json.put("statusCode", -1);
        json.put("msg","您还未登陆，无法操作");
        json.put("log", "时间："+ df.format(new Date())+" IP:"+getIpAddress(request));
        return json;
    }

    /**
     * 该方法是在Controller执行之后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //处理错误页面
        int HTTPstatusCode = response.getStatus();
        if(HTTPstatusCode==200){

        }else {
            response.setHeader("content-type","application:json;charset=utf8");
            JSONObject json = errorType(request,HTTPstatusCode);
            response.getWriter().write(json.toJSONString());
        }
    }

    public JSONObject errorType(HttpServletRequest request,int type){
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        JSONObject json=new JSONObject();
        json.put("statusCode", -1);
        json.put("msg","服务器繁忙 "+type);
        json.put("log", "时间："+ df.format(new Date())+" IP:"+getIpAddress(request));
        return json;
    }

    /**
     * 该方法在整个请求完成之后执行，主要用于清理资源
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    // 获取IP
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
